package net.maku.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import net.maku.api.module.storage.StorageService;
import net.maku.enums.AuditStateEnum;
import net.maku.framework.common.page.PageResult;
import net.maku.framework.common.utils.Result;
import net.maku.convert.WillPayItemConvert;
import net.maku.entity.WillPayItemEntity;
import net.maku.query.WillPayItemAuditQuery;
import net.maku.query.WillPayItemDashBoardQuery;
import net.maku.query.WillPayItemModifyQuery;
import net.maku.service.WillPayItemService;
import net.maku.query.WillPayItemQuery;
import net.maku.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.xml.ws.Response;
import java.io.IOException;
import java.util.List;

/**
* 应付款管理
*
* @author 中国华 hualaihu@126.com
* @since 1.0-SNAPSHOT 2022-08-29
*/
@RestController
@RequestMapping("will/pay")
@Tag(name="应付款管理")
@AllArgsConstructor
public class WillPayItemController {
    private final WillPayItemService willPayItemService;
    private final StorageService storageService;


    @GetMapping("audit/page")
    @Operation(summary = "待审核分页")
    @PreAuthorize("hasAuthority('willpayaudit:page')")
    public Result<PageResult<waitAuditItem>> auditPage(@Valid WillPayItemAuditQuery query){

        PageResult<waitAuditItem> page = willPayItemService.auditPage(query);

        return Result.ok(page);
    }

    @GetMapping("modify/page")
    @Operation(summary = "待修改分页")
    @PreAuthorize("hasAuthority('willpaymodify:page')")
    public Result<PageResult<waitModifyItem>> auditPage(@Valid WillPayItemModifyQuery query){

        PageResult<waitModifyItem> page = willPayItemService.modifyPage(query);

        return Result.ok(page);
    }

    @PostMapping("page")
    @Operation(summary = "应付款分页")
    @PreAuthorize("hasAuthority('willpayitem:page')")
    public Result<PageResult<WillPayItemVO>> page(@RequestBody @Valid WillPayItemQuery query){
        PageResult<WillPayItemVO> page = willPayItemService.page(query);

        return Result.ok(page);
    }

    @GetMapping("{id}")
    @Operation(summary = "查看")
    @PreAuthorize("hasAuthority('willpayitem:info')")
    public Result<WillPayItemVO> get(@PathVariable("id") Long id){
        WillPayItemEntity entity = willPayItemService.getById(id);

        return Result.ok(WillPayItemConvert.INSTANCE.convert(entity));
    }

    @PostMapping
    @Operation(summary = "保存")
    @PreAuthorize("hasAuthority('willpayitem:save')")
    public Result<String> save(@RequestBody @Valid WillPayItemAddVO vo){
        willPayItemService.save(vo);

        return Result.ok();
    }

    @GetMapping("download")
    @Operation(summary = "下载文件")
    @Parameter(name = "url", description = "文件url地址，智能付款模板地址为{服务端地址+智能付款模板.xlsx，开发环境：http://192.168.8.254:8116/template/%E6%99%BA%E8%83%BD%E4%BB%98%E6%AC%BE%E6%A8%A1%E6%9D%BF.xlsx}", required = true)
    public String download(HttpServletResponse response,
                                          @RequestParam String url){
        try {
            storageService.download(response, url);
        } catch (IOException e) {
            e.printStackTrace();
            return "1";
        }
        return "0";
    }

    @Operation(summary = "上传智能付款文件")
    @PostMapping("import")
    @PreAuthorize("hasAuthority('willpayitem:save')")
    public Result<String> importExcel(@RequestParam("file") MultipartFile file) {
        String resultFile = willPayItemService.importExcel(file);
        if (StringUtils.hasText(resultFile)){
           return Result.error(resultFile);
        }
        return Result.ok();
    }

    @GetMapping("export/all")
    @Operation(summary = "导出所有")
    @PreAuthorize("hasAuthority('payitem:export')")
    public void exportAll(HttpServletResponse response){

        willPayItemService.exportAll(response);

    }

    @PutMapping
    @Operation(summary = "待审核-修改")
    @PreAuthorize("hasAuthority('willpayitem:update')")
    public Result<String> update(@RequestBody @Valid WillPayItemEditVO vo){

        WillPayItemUpdateVO update = WillPayItemConvert.INSTANCE.editConvertUpdate(vo);
        willPayItemService.update(update);

        return Result.ok();
    }

    /*
    @PutMapping("correct")
    @Operation(summary = "重新编辑（针对审核拒绝记录）")
    @PreAuthorize("hasAuthority('willpayitem:correct')")
    public Result<String> correct(@RequestBody @Valid WillPayItemEditVO vo){

        WillPayItemUpdateVO update = WillPayItemConvert.INSTANCE.editConvertUpdate(vo);
        update.setAuditState(AuditStateEnum.AUDIT_WAIT.getValue());
        willPayItemService.update(update);

        return Result.ok();
    }*/

    @DeleteMapping
    @Operation(summary = "删除")
    @PreAuthorize("hasAuthority('willpayitem:delete')")
    public Result<String> delete(@RequestBody List<Long> idList){
        willPayItemService.delete(idList);

        return Result.ok();
    }

    @PutMapping("batch/audit")
    @Operation(summary = "批量审核")
    @PreAuthorize("hasAuthority('willpayitem:audit')")
    public Result<String> audit(@RequestBody @Valid List<WillPayItemAuditVO> vo){
        willPayItemService.auditBatch(vo);
        return Result.ok();
    }

    @PutMapping("degree/batch/set")
    @Operation(summary = "批量设置紧急级别")
    @PreAuthorize("hasAuthority('willpayitem:setlevel')")
    public Result<String> batchSetDegree(@RequestBody @Valid List<WillPayItemSetDegreeVO> vo){
        willPayItemService.batchSetDegree(vo);
        return Result.ok();
    }

    @PutMapping("pay/batch/set")
    @Operation(summary = "批量设置已付款")
    @PreAuthorize("hasAuthority('willpayitem:setpayed')")
    public Result<String> batchSetPayed(@RequestBody @Valid List<Long> ids){
        willPayItemService.batchSetPayed(ids);
        return Result.ok();
    }

    @PutMapping("/reback/{id}")
    @Operation(summary = "撤销")
    @PreAuthorize("hasAuthority('willpayitem:setreback')")
    public Result<String> setReback(@PathVariable("id") Long id){
        willPayItemService.setReback(id);

        return Result.ok();
    }

    @GetMapping("emergency/degree/stats")
    @Operation(summary = "H5-统计紧急级别数量")
    @PreAuthorize("hasAuthority('willpaydashboard:info')")
    public Result<EmergencyDegreeStatsVO> statsEmergencyDegree(){
        return Result.ok(willPayItemService.statsEmergencyDegree());
    }

    @PostMapping("dashboard")
    @Operation(summary = "H5-看板")
    @PreAuthorize("hasAuthority('willpaydashboard:info')")
    public Result<List<WillPayItemDashBoardVO>> dashboard(@RequestBody @Valid WillPayItemDashBoardQuery query){
        List<WillPayItemDashBoardVO> list = willPayItemService.dashboard(query);
        return Result.ok(list);
    }
}